<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="设备名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入设备编号"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceId">
                <el-input
                    v-model="queryParams.deviceId"
                    placeholder="请输入设备编号"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="instanceList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="设备名称" align="center" prop="name">
                <template slot-scope="scope">
                    <el-link :underline="false" type="primary"
                             @click.native="handleViewInstance(scope.row)"
                    >
                        {{ scope.row.name }}
                    </el-link>
                </template>
            </el-table-column>

            <el-table-column label="设备编号" align="center" prop="deviceId"/>
            <el-table-column label="产品" align="center" prop="productId"/>
            <el-table-column label="设备类型" align="center" prop="deviceType">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.device_type" :value="scope.row.deviceType"/>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.device_state" :value="scope.row.state"/>
                </template>
            </el-table-column>
            <el-table-column label="最后上线时间" align="center" prop="createTime">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.onlineTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="离线时间" align="center" prop="createTime">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.offlineTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleUpdate(scope.row)"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleDelete(scope.row)"
                    >删除
                    </el-button>
<!--                    <el-button-->
<!--                        size="mini"-->
<!--                        type="text"-->
<!--                        @click="handleViewProduct(scope.row)"-->
<!--                    >产品-->
<!--                    </el-button>-->
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleParameterSetting(scope.row)"
                    >参数设置
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNo"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改设备对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="设备名称" prop="name" label-width="100px">
                    <el-input v-model="form.name" placeholder="请输入设备名称"/>
                </el-form-item>
                <el-form-item label="设备编号" prop="deviceId" label-width="100px">
                    <el-input v-model="form.deviceId" placeholder="请输入设备编号"/>
                </el-form-item>
                <el-form-item label="产品" prop="productId" label-width="100px">
                    <el-select v-model="form.productId" placeholder="产品" clearable>
                        <el-option
                            v-for="item in productList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>

        </el-dialog>

        <!-- 产品详情对话框 -->
        <el-dialog :title="'产品详情'" :visible.sync="productDialogVisible" width="800px" append-to-body>
            <el-descriptions :column="1" border>
                <el-descriptions-item label="产品名称">{{ productInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="产品编号">{{ productInfo.id }}</el-descriptions-item>
                <el-descriptions-item label="设备类型">{{ productInfo.deviceType }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ parseTime(productInfo.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ productInfo.remark || '无' }}</el-descriptions-item>
            </el-descriptions>

            <div class="metadata-section" style="margin-top: 20px;">
                <h3>设备属性配置</h3>
                <el-table :data="metadataProperties" border style="width: 100%">
                    <el-table-column prop="name" label="属性名称" width="180"></el-table-column>
                    <el-table-column prop="id" label="属性ID" width="180"></el-table-column>
                    <el-table-column prop="valueType.type" label="数据类型"></el-table-column>
                    <el-table-column label="配置项">
                        <template slot-scope="scope">
                            <el-table :data="scope.row.expands.configs" border size="mini">
                                <el-table-column prop="name" label="配置名称"></el-table-column>
                                <el-table-column prop="value" label="配置值"></el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button @click="productDialogVisible = false">关 闭</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    listInstance,
    getInstance,
    delInstance,
    addInstance,
    updateInstance,
    updateInstanceProperty
} from '@/api/device/instance'
import { listProductSelect,getDeviceProduct } from '@/api/device/product'

export default {
    name: 'Instance',
    dicts: ['biz_product', 'device_state', 'device_type'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 设备表格数据
            instanceList: [],
            productList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNo: 1,
                pageSize: 10,
                deviceId: null,
                name: null,
                deviceType:6,
                productId: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                deviceId: [
                    { required: true, message: '设备编号不能为空', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '设备名称不能为空', trigger: 'blur' }
                ],
                productId: [
                    { required: true, message: '产品不能为空', trigger: 'blur' }
                ],
            },
            // 播报规则弹出层
            radioRuleOpen: false,
            // 播报规则表单
            radioRuleForm: {
                id: null,
                radioRule: []
            },
            // 产品详情对话框
            productDialogVisible: false,
            // 产品信息
            productInfo: {},
            // 元数据属性列表
            metadataProperties: [],
        }
    },
    created() {
        this.getList()
        this.getProductData()
    },
    methods: {
        // 获取产品下拉
        getProductData() {
            listProductSelect().then(res => {
                this.productList = res.data
            })
        },
        getList() {
            this.loading = true
            listInstance(this.queryParams).then(response => {
                this.instanceList = response.data.list
                this.total = response.data.total
                this.loading = false
            })
        },

        cancel() {
            this.open = false
            this.reset()
            this.contentStr = ''

        },

        reset() {
            this.form = {
                id: null,
                deviceId: null,
                name: null,
                productId: null
            }
            this.resetForm('form')
        },

        handleQuery() {
            this.queryParams.pageNo = 1
            this.getList()
        },

        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },

        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加设备'
        },
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getInstance(id).then(response => {
                this.form = response.data
                this.open = true
                console.log(this.form)
                this.title = '修改设备'
            })
        },
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateInstance(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addInstance(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },

        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除设备编号为"' + ids + '"的数据项？').then(function() {
                return delInstance(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },

        handleExport() {
            this.download('stock/bizScreen/export', {
                ...this.queryParams
            }, `bizScreen_${new Date().getTime()}.xlsx`)
        },

        // 查看产品详情
        handleViewProduct(row) {
            getDeviceProduct(row.productId).then(response => {
                this.productInfo = response.data;
                // 解析metadata
                if (this.productInfo.metadata) {
                    try {
                        const metadata = JSON.parse(this.productInfo.metadata);
                        console.log('mete',metadata)
                        this.metadataProperties = metadata.properties || [];
                    } catch (e) {
                        console.error('解析metadata失败:', e);
                        this.metadataProperties = [];
                    }
                }
                this.productDialogVisible = true;
            });
        },
        // 查看属性详情
        handleViewInstance(row) {
            // console.log('row.deviceId',row.deviceId)
            let obj ={
                deviceId:row.deviceId,
                productId:row.productId
            }
            this.$router.push({
                path: '/equipment/riceHuskingMachine/detail',
                query: obj
            })
        },
        // 参数设置
        handleParameterSetting(row) {
            // console.log('row.deviceId',row.deviceId)
            let obj ={
                deviceId:row.deviceId,
                productId:row.productId
            }
            this.$router.push({
                path: '/equipment/riceHuskingMachine/parameterSetting',
                query: obj
            })
        },
    }
}
</script>

<style scoped>
.metadata-section {
    margin-top: 20px;
}
.metadata-section h3 {
    margin-bottom: 15px;
    font-weight: 500;
    color: #303133;
}
</style>
